package ventanas;
/*
import beans.Abonos;
import beans.Alquileres;
import beans.Articulos;
import beans.Articulosdocumento;
import beans.Detallefactura;
import beans.Documentos;
import beans.Facturapropiedades;
import beans.Movimientokardex;
import beans.Terceros;
import interfaces.Buscadores;
import java.awt.Frame;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import managers.ManejadorArticulos;
import managers.ManejadorConfiguraciones;
import managers.ManejadorDocumentos;
import managers.Model;
import utilidades.Calendario;
import utilidades.Fechavo;

public class Formulario_Prefactura extends javax.swing.JDialog {

    /** Creates new form Formulario_Prefactura 
    Documentos d;
    Articulosdocumento ad;
    Alquileres al;
    ManejadorArticulos ma;
    ManejadorDocumentos md;
    ManejadorConfiguraciones mc;
    int funcion = 0;
    Buscadores b;
    DefaultTableModel mt = new DefaultTableModel();
    DefaultTableModel mtabonos = new DefaultTableModel();
    Model m;
    Frame parent;

    public Formulario_Prefactura(java.awt.Frame parent, boolean modal, Buscadores b, Model m) {

        super(parent, modal);
        this.parent = parent;
        this.b = b;
        this.m = m;
        ma = new ManejadorArticulos(m);
        md = new ManejadorDocumentos(m);
        mc = new ManejadorConfiguraciones(m);
        d = new Documentos();
        init();
        int ano = Calendar.getInstance().get(Calendar.YEAR);
        int mes = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int dia = Calendar.getInstance().get(Calendar.DATE);

        fecha.setText(ano + "-" + mes + "-" + dia);

        Facturapropiedades fp = mc.getFacturaporpiedades("1");
        if (fp != null) {
            long consecutivo = fp.getPrefacturas().longValue() + 1;
            numero.setText(consecutivo + "");
        } else {
            JOptionPane.showMessageDialog(null, "no se ha Configuarado las propiedades de la factura");
            guardar.setEnabled(false);
        }

        tabla.setModel(mt);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public Formulario_Prefactura(java.awt.Frame parent, boolean modal, Buscadores b, Documentos d, Model m) {

        super(parent, modal);
        this.parent = parent;
        this.b = b;
        this.m = m;
        this.d = d;
        ma = new ManejadorArticulos(m);
        md = new ManejadorDocumentos(m);
        mc = new ManejadorConfiguraciones(m);

        init();
        llenar();
        tabla.setModel(mt);
        this.setLocationRelativeTo(null);
        this.setVisible(true);

    }

    public void init() {
        ma = new ManejadorArticulos(m);
        md = new ManejadorDocumentos(m);
        mc = new ManejadorConfiguraciones(m);

        initComponents();
        tab.remove(panelabonos);
        setTitle("Prefacturas");
        tercero.requestFocus();
        mt.addColumn("Codigo");
        mt.addColumn("Descripcion");
        mt.addColumn("Cantidad");
        mt.addColumn("Vlr Unit");
        mt.addColumn("Vlr Par");
        utilidades.FormatoNumeros fn = new utilidades.FormatoNumeros(descuento);
        descuento.addKeyListener(fn);
        descuento.addFocusListener(fn);

        fn = new utilidades.FormatoNumeros(vunit);
        vunit.addKeyListener(fn);
        vunit.addFocusListener(fn);

        fn = new utilidades.FormatoNumeros(vparcial);
        vparcial.addKeyListener(fn);
        vparcial.addFocusListener(fn);

        utilidades.FormatoCantidades fc = new utilidades.FormatoCantidades(cantidad);
        cantidad.addKeyListener(fc);
        cantidad.addFocusListener(fc);

        adicionar.setEnabled(false);
        articulo.setText("");
        cantidad.setText("1");
        vunit.setText("0.00");
        vparcial.setText("0.00");

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        fecha = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        numero = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        salir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tab = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        articulo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cantidad = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        vunit = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        vparcial = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        quitar = new javax.swing.JButton();
        adicionar = new javax.swing.JButton();
        buscara = new javax.swing.JButton();
        total = new javax.swing.JLabel();
        tipo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        nota = new javax.swing.JTextField();
        descuento = new javax.swing.JTextField();
        subtotal = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        tipodescuento = new javax.swing.JComboBox();
        panelabonos = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaabonos = new javax.swing.JTable();
        agregar = new javax.swing.JButton();
        totalpagado = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        saldo = new javax.swing.JLabel();
        guardar = new javax.swing.JButton();
        buscafecha = new javax.swing.JButton();
        tercero = new javax.swing.JTextField();
        buscaproveedor = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        ntercero = new javax.swing.JTextField();
        restaurar = new javax.swing.JButton();
        guardar1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Prefacturas");

        jPanel2.setBackground(new java.awt.Color(212, 233, 255));

        fecha.setEditable(false);

        jLabel4.setText("Fecha");

        numero.setEditable(false);
        numero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                numeroActionPerformed(evt);
            }
        });
        numero.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                numeroKeyTyped(evt);
            }
        });

        jLabel2.setText("Numero");

        salir.setBackground(new java.awt.Color(0, 153, 255));
        salir.setFont(new java.awt.Font("Tahoma", 1, 11));
        salir.setForeground(new java.awt.Color(0, 51, 153));
        salir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/bulletCritical.png"))); // NOI18N
        salir.setText("Salir");
        salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirActionPerformed(evt);
            }
        });

        jLabel1.setBackground(new java.awt.Color(0, 153, 255));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setForeground(new java.awt.Color(0, 51, 153));

        jPanel1.setBackground(new java.awt.Color(153, 205, 255));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Descripcion", "Cantidad", "Vlr Unit", "Vlr Par"
            }
        ));
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        articulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                articuloActionPerformed(evt);
            }
        });

        jLabel3.setText("Articulo");

        cantidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cantidadActionPerformed(evt);
            }
        });

        jLabel5.setText("Cantidad");

        vunit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vunitActionPerformed(evt);
            }
        });

        jLabel6.setText("Vlr Unit");

        jLabel7.setText("Vlr Par");

        quitar.setForeground(new java.awt.Color(0, 0, 204));
        quitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cerrar.png"))); // NOI18N
        quitar.setText("Quitar");
        quitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitarActionPerformed(evt);
            }
        });

        adicionar.setForeground(new java.awt.Color(0, 0, 204));
        adicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        adicionar.setText("Adicionar");
        adicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adicionarActionPerformed(evt);
            }
        });

        buscara.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-16x16.png"))); // NOI18N
        buscara.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscaraActionPerformed(evt);
            }
        });

        total.setFont(new java.awt.Font("Tahoma", 1, 24));
        total.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        total.setText("0.00");

        tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Articulo", "Servicio", "Arriendo" }));

        jLabel9.setText("Tipo");

        jLabel11.setText("Nota");

        descuento.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        descuento.setText("0.00");
        descuento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                descuentoActionPerformed(evt);
            }
        });
        descuento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                descuentoKeyReleased(evt);
            }
        });

        subtotal.setEditable(false);
        subtotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        subtotal.setText("0.00");

        jLabel13.setText("Subtotal");

        jLabel14.setText("Descuento");

        tipodescuento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "%", "$" }));
        tipodescuento.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tipodescuentoItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(buscara, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(articulo, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel9)
                                        .addGap(77, 77, 77))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addComponent(vunit, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel7)
                                        .addGap(64, 64, 64)
                                        .addComponent(total, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(vparcial, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(adicionar)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(quitar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(nota, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                                .addGap(63, 63, 63)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel13)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(tipodescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel14)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(descuento)
                                    .addComponent(subtotal, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))))
                        .addGap(240, 240, 240))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 702, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel9)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6)
                                .addComponent(jLabel7))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(buscara)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(articulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(vunit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(vparcial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(adicionar))))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(total)))
                .addGap(13, 13, 13)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(quitar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel11)
                                .addComponent(nota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(34, 34, 34))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(subtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(descuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel14)
                            .addComponent(tipodescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );

        tab.addTab("Detalles", jPanel1);

        panelabonos.setBackground(new java.awt.Color(212, 233, 255));

        tablaabonos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Fecha", "Valor"
            }
        ));
        jScrollPane2.setViewportView(tablaabonos);

        agregar.setForeground(new java.awt.Color(0, 51, 153));
        agregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        agregar.setText("Agregar");
        agregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarActionPerformed(evt);
            }
        });

        totalpagado.setFont(new java.awt.Font("Tahoma", 1, 14));
        totalpagado.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalpagado.setText("0.00");

        jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel16.setText("Total");

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel15.setText("Saldo");

        saldo.setFont(new java.awt.Font("Tahoma", 1, 18));
        saldo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        saldo.setText("0.00");

        javax.swing.GroupLayout panelabonosLayout = new javax.swing.GroupLayout(panelabonos);
        panelabonos.setLayout(panelabonosLayout);
        panelabonosLayout.setHorizontalGroup(
            panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelabonosLayout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addGroup(panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelabonosLayout.createSequentialGroup()
                        .addComponent(jLabel15)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saldo, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelabonosLayout.createSequentialGroup()
                            .addComponent(agregar)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel16)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(totalpagado, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 761, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        panelabonosLayout.setVerticalGroup(
            panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelabonosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(saldo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(panelabonosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalpagado)
                    .addComponent(jLabel16)
                    .addComponent(agregar))
                .addContainerGap(54, Short.MAX_VALUE))
        );

        tab.addTab("Abonos", panelabonos);

        guardar.setBackground(new java.awt.Color(0, 153, 255));
        guardar.setFont(new java.awt.Font("Tahoma", 1, 11));
        guardar.setForeground(new java.awt.Color(0, 51, 153));
        guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok.png"))); // NOI18N
        guardar.setText("Guardar");
        guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarActionPerformed(evt);
            }
        });

        buscafecha.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Calendar-16x16.png"))); // NOI18N
        buscafecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscafechaActionPerformed(evt);
            }
        });

        tercero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                terceroActionPerformed(evt);
            }
        });

        buscaproveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-16x16.png"))); // NOI18N
        buscaproveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscaproveedorActionPerformed(evt);
            }
        });

        jLabel10.setText("Cliente");

        ntercero.setEditable(false);

        restaurar.setBackground(new java.awt.Color(0, 155, 255));
        restaurar.setText("Restaurar");
        restaurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                restaurarActionPerformed(evt);
            }
        });

        guardar1.setBackground(new java.awt.Color(0, 153, 255));
        guardar1.setFont(new java.awt.Font("Tahoma", 1, 11));
        guardar1.setForeground(new java.awt.Color(0, 51, 153));
        guardar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok.png"))); // NOI18N
        guardar1.setText("Guardar Como Factura");
        guardar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardar1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(187, 187, 187)
                        .addComponent(jLabel1))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(tab, javax.swing.GroupLayout.PREFERRED_SIZE, 736, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(160, 160, 160)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buscafecha, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(numero, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(tercero, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(ntercero)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buscaproveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(113, 113, 113)
                        .addComponent(restaurar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardar1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(salir, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel4))
                            .addComponent(buscafecha)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(numero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(16, 16, 16)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tercero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10)
                            .addComponent(ntercero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(buscaproveedor)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tab, javax.swing.GroupLayout.PREFERRED_SIZE, 398, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(restaurar)
                    .addComponent(salir)
                    .addComponent(guardar)
                    .addComponent(guardar1))
                .addGap(17, 17, 17))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void numeroKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_numeroKeyTyped
        // TODO add your handling code here:
        if (!Character.isDigit(evt.getKeyChar())) {
            evt.consume();
        }
}//GEN-LAST:event_numeroKeyTyped

    private void salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirActionPerformed
        // TODO add your handling code here:
        this.dispose();
        //   tab.remove(dp);
}//GEN-LAST:event_salirActionPerformed

    private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed
        // TODO add your handling code here:
        boolean sw = true;
        if (validar()) {
            if (funcion == 1) {
                //  JOptionPane.showMessageDialog(null,d.getNumero()+" "+numero.getText());
                if (d.getNumero().equals(numero.getText())) {
                    guardar();
                    sw = false;
                }
            }
            if (sw) {
                if (!md.existeDocumento("numero", numero.getText())) {
                    guardar();
                } else {
                    JOptionPane.showMessageDialog(null, "Numero de Factura ya exsiste");
                }
            }
        }
}//GEN-LAST:event_guardarActionPerformed

    public void guardar() {

        Facturapropiedades fp = mc.getFacturaporpiedades("1");
        d.setNumero("" + (fp.getPrefacturas() + 1));
        d.setFecha(new Date(fecha.getText().replaceAll("-", "/")));
        d.setTotal(Double.parseDouble(total.getText()));
        d.setNota(nota.getText());
        d.setTipo(0);
        d.setEstado(0);
        List<Alquileres> lal = new LinkedList();
        List<Articulosdocumento> la = new LinkedList();

        if (d.getAlquileresCollection() != null) {
            for (int i = 0; i < d.getAlquileresCollection().size(); i++) {
                md.eliminar(d.getAlquileresCollection().get(i));
            }
        }

        if (d.getArticulosdocumentoCollection() != null) {
            for (int i = 0; i < d.getArticulosdocumentoCollection().size(); i++) {
                md.eliminar(d.getArticulosdocumentoCollection().get(i));
            }
        }
       
        for (int i = 0; i < tabla.getRowCount(); i++) {

            if (tabla.getValueAt(i, 0) instanceof Alquileres) {
                Alquileres al = (Alquileres) tabla.getValueAt(i, 0);
                al.setEstado(0);
                al.setDocumento(d);
                lal.add(al);
            } else {
                Articulosdocumento ad = (Articulosdocumento) tabla.getValueAt(i, 0);
                ad.setDocumento(d);
                la.add(ad);
            }
        }

        d.setAlquileresCollection(lal);
        d.setArticulosdocumentoCollection(la);

        if (funcion == 0) {

            fp.setPrefacturas((fp.getPrefacturas() + 1));
            mc.modificar(fp);
            md.crear(d);
        } else {
            md.modificar(d);
        }
        b.buscar();
        this.dispose();
        JOptionPane.showMessageDialog(null, "Datos guardados con exito");
    }

    public boolean validar() {
        if (numero.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite el NUMERO porfavor");
            numero.requestFocus();
            return false;
        } else if (fecha.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite la FECHA porfavor");
            fecha.requestFocus();
            return false;
        } else if (tercero.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite el TERCERO porfavor");
            fecha.requestFocus();
            return false;
        } else {
            if (d.getTipo() != 1) {
                if (!this.comprovarExitencia()) {
                    JOptionPane.showMessageDialog(null, "Los Articulos en rojo tienen una cantidad mayor a la exitencia, Editelos");
                    return false;
                }
            }
        }
        return true;
    }

    public void llenar() {

        numero.setText(d.getNumero());
        fecha.setText(new java.text.SimpleDateFormat("yyyy-MM-dd").format(d.getFecha()));
        tercero.setText(d.getTerceros().getNit() + "");
        ntercero.setText(d.getTerceros().getNombre());
        List<Articulosdocumento> la = d.getArticulosdocumentoCollection();
        List<Alquileres> lal = d.getAlquileresCollection();
        funcion = 1;
        double totales = 0.0;
        for (int i = 0; i < la.size(); i++) {
            Articulos a1 = la.get(i).getArticulo();
            double cantidades = la.get(i).getCantidad();
            mt.addRow(new Object[]{la.get(i), a1.getDescripcioncomercial(), utilidades.FormatoNumeros.formatearCantidades(cantidades + ""), la.get(i).getVlrunitario(), la.get(i).getVlrparcial()});
            totales += (la.get(i).getVlrparcial());

        }
        for (int i = 0; i < lal.size(); i++) {
            Articulos a1 = lal.get(i).getArticulo();
            int cantidades = lal.get(i).getCantidad();
            mt.addRow(new Object[]{lal.get(i), a1.getDescripcioncomercial(), cantidades, lal.get(i).getVlrunitario(), lal.get(i).getTotal()});
            totales += (lal.get(i).getTotal());

        }

        total.setText(totales + "");
    }

    public boolean comprovarExitencia() {
        boolean sw = true;
        Vector tot = new Vector();
        for (int i = 0; i < tabla.getRowCount(); i++) {
            if (tabla.getValueAt(i, 0) instanceof Articulosdocumento) {
                Articulosdocumento ad = (Articulosdocumento) tabla.getValueAt(i, 0);
                if (ad.getCantidad() > ma.getArticulo(ad.getArticulo().getId() + "").getExistencia().longValue()) {
                    tot.add(i);
                    sw = false;
                }
            }
        }

        if (!sw) {
            int toteados[] = new int[tot.size()];
            for (int i = 0; i < tot.size(); i++) {
                toteados[i] = i;

            }
            utilidades.TablaRender tabre = new utilidades.TablaRender();
            tabre.setToteados(toteados);
            System.out.println(toteados.length);

            mt = new DefaultTableModel();
            mt.addColumn("Codigo");
            mt.addColumn("Descripcion");
            mt.addColumn("Cantidad");
            mt.addColumn("Vlr Unit");
            mt.addColumn("Vlr Par");
            tabla.setDefaultRenderer(Object.class, tabre);
            llenarModel();
            tabla.setModel(mt);
        }
        return sw;

    }

    public void llenarModel() {
        List<Articulosdocumento> la = d.getArticulosdocumentoCollection();
        List<Alquileres> lal = d.getAlquileresCollection();
        if (la != null) {
            for (int i = 0; i < la.size(); i++) {
                Articulos a1 = la.get(i).getArticulo();
                double cantidades = la.get(i).getCantidad();
                mt.addRow(new Object[]{la.get(i), a1.getDescripcioncomercial(), cantidades, utilidades.FormatoNumeros.formatear(la.get(i).getVlrunitario() + ""), utilidades.FormatoNumeros.formatear(la.get(i).getVlrparcial() + "")});
            }
        }
        if (lal != null) {
            for (int i = 0; i < lal.size(); i++) {
                Articulos a1 = lal.get(i).getArticulo();
                int cantidades = lal.get(i).getCantidad();
                mt.addRow(new Object[]{lal.get(i), a1.getDescripcioncomercial(), cantidades, utilidades.FormatoNumeros.formatear(lal.get(i).getVlrunitario() + ""), utilidades.FormatoNumeros.formatear(lal.get(i).getTotal() + "")});
            }
        }

    }

    private void quitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitarActionPerformed
        // TODO add your handling code here:
        if (tabla.getSelectedRow() > -1) {
            double totales = Double.parseDouble(total.getText());
            totales -= Double.parseDouble("" + tabla.getValueAt(tabla.getSelectedRow(), 4));
            mt.removeRow(tabla.getSelectedRow());
            total.setText("" + totales);
        } else {
            JOptionPane.showMessageDialog(null, "No hay Articulo Seleccionado");
        }
}//GEN-LAST:event_quitarActionPerformed

    private void adicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adicionarActionPerformed
        // TODO add your handling code here:
        double cantidades = Double.parseDouble(cantidad.getText());
        if (ad != null) {///si es un articulo documento
            if (!esta(ad)) {
                String descrip = ad.getArticulo().getDescripcioncomercial();
                if (ad.getArticulo().getTipo() == 1) {
                    descrip = "Servicio de " + ad.getArticulo().getDescripcioncomercial();
                }
                double totalparcial = Double.parseDouble(this.vparcial.getText().replaceAll(",", ""));
                double totales = Double.parseDouble(total.getText().replaceAll(",", ""));
                ad.setCantidad(cantidades);
                ad.setVlrunitario(Double.parseDouble(this.vunit.getText().replaceAll(",", "")));
                ad.setVlrparcial(totalparcial);
                double existencia = ad.getArticulo().getExistencia().longValue() - cantidades;
                ad.getArticulo().setExistencia((existencia));

                mt.addRow(new Object[]{ad, descrip, cantidad.getText(), utilidades.FormatoNumeros.formatear(vunit.getText()), utilidades.FormatoNumeros.formatear(vparcial.getText())});
                totales += (totalparcial);
                total.setText(utilidades.FormatoNumeros.formatear(totales + ""));
                subtotal.setText(utilidades.FormatoNumeros.formatear(totales + ""));
                ad = null;
                adicionar.setEnabled(false);
                articulo.setText("");
                cantidad.setText("1");
                vunit.setText("0.00");
                vparcial.setText("0.00");
            } else {
                JOptionPane.showConfirmDialog(null, "El Articulo ya esta adicionado");
            }
        } else {
            if (al != null) {/// si es un alquiler
                if (!esta(al)) {
                    String descrip = "Arriendo de " + al.getArticulo().getDescripcioncomercial();
                    double totalparcial = Double.parseDouble(this.vparcial.getText().replaceAll(",", ""));
                    double totales = Double.parseDouble(total.getText().replaceAll(",", ""));
                    double vunitario = Double.parseDouble(vunit.getText().replaceAll(",", ""));
                    al.setCantidad((int) cantidades);
                    al.setTotal(totalparcial);
                    al.setVlrunitario(vunitario);
                    mt.addRow(new Object[]{al, descrip, cantidad.getText(), this.vunit.getText(), totalparcial});
                    totales += (totalparcial);
                    total.setText(totales + "");
                    al = null;
                    articulo.requestDefaultFocus();
                    adicionar.setEnabled(false);
                } else {
                    JOptionPane.showConfirmDialog(null, "El Articulo ya esta adicionado");
                }
            } else {
                JOptionPane.showConfirmDialog(null, "Seleccione un Articulo");
            }
        }
    }//GEN-LAST:event_adicionarActionPerformed

    private void buscaraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscaraActionPerformed
        // TODO add your handling code here:
        Articulos a = null;
        if (tipo.getSelectedIndex() == 2) {
            al = new BuscaArticuloParaAriendo((Frame) this.getParent(), true, m).getArticulo();
        } else {
            a = new BuscaArticulo((Frame) this.getParent(), true, m).getArticulo();
            if (a != null) {
                ad = new Articulosdocumento();
                ad.setArticulo(a);
            }
        }
        if (a != null || al != null) {
            articulo.setText("" + (al == null ? ad.getArticulo().getDescripcioncomercial() : al.getArticulo().getDescripcioncomercial()));
            vunit.setText("" + (al == null ? ad.getArticulo().getVlrpromediov() : al.getArticulo().getVlrpromediov()));
            cantidad.requestFocus();
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione un Articulo");
        }
}//GEN-LAST:event_buscaraActionPerformed

    private void buscafechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscafechaActionPerformed
        // TODO add your handling code here:
        fecha.setText(new Calendario((Frame) this.getParent(), true).getFecha());
        numero.requestFocus();
}//GEN-LAST:event_buscafechaActionPerformed

    private void articuloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_articuloActionPerformed
        // TODO add your handling code here:
        if (articulo.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite Codigo de Barras");
        } else if (tipo.getSelectedIndex() == 0 || tipo.getSelectedIndex() == 1 || tipo.getSelectedIndex() == 3) {

            Articulos a = ma.getArticulo("codigobarras", BigInteger.valueOf(Long.parseLong(articulo.getText())));
            if (a == null) {
                JOptionPane.showMessageDialog(null, "Articulo no Existe ");
            } else {
                if (!esta(a)) {
                    ad = new Articulosdocumento();
                    ad.setArticulo(a);
                    cantidad.requestFocus();
                } else {
                    JOptionPane.showConfirmDialog(null, "El Articulo ya esta adicionado");
                }
            }
        } else {
            JOptionPane.showConfirmDialog(null, "El Articulo es de ARRIENDO seleccionelo por el buscador ");
        }
    }//GEN-LAST:event_articuloActionPerformed

    private void cantidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cantidadActionPerformed
        // TODO add your handling code here:
        Double cantidades = Double.parseDouble(cantidad.getText());
        if (cantidad.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite una CANTIDAD");
        } else {
            long existencia = ad != null ? ad.getArticulo().getExistencia().longValue() : al.getArticulo().getExistencia().longValue();
            if (cantidades <= existencia) {

                double totalparcial = cantidades * (ad != null ? ad.getArticulo().getVlrpromediov() : al.getArticulo().getVlrpromediov());
                if (al != null) {
                    SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
                    //  System.out.println(" "+formato.format(al.getFechaIni())+" "+formato.format(al.getFechaFin()));
                    int dias = new Fechavo().diasDeDiferencia(formato.format(al.getFechaIni()), formato.format(al.getFechaFin()));
                    totalparcial = cantidades * al.getArticulo().getVlrpromediov() * dias;
                }

                vparcial.setText("" + utilidades.FormatoNumeros.formatear("" + totalparcial));
                adicionar.setEnabled(true);
                vunit.requestFocus();
            } else {
                JOptionPane.showMessageDialog(null, "La cantidad digitada es mayor a la disponibilidad o exitencia del articulo");
            }
        }
    }//GEN-LAST:event_cantidadActionPerformed

    private void buscaproveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscaproveedorActionPerformed
        // TODO add your handling code here:
        d.setTerceros(new BuscaTerceros((Frame) this.getParent(), true, m).getTercero());
        if (d.getTerceros() != null) {
            tercero.setText(d.getTerceros().getNit() + "");
            ntercero.setText(d.getTerceros().getNombre());
            articulo.requestFocus();
        }
    }//GEN-LAST:event_buscaproveedorActionPerformed

    private void numeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_numeroActionPerformed
        // TODO add your handling code here:
        tercero.requestFocus();
    }//GEN-LAST:event_numeroActionPerformed

    private void terceroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_terceroActionPerformed
        // TODO add your handling code here:
        if (tercero.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite el nit del Tercero ");
        } else if (md.getTercero((Object) tercero.getText()) != null) {
            d.setTerceros(md.getTercero((Object) tercero.getText()));
            tercero.setText(d.getTerceros().getNit() + "");
            ntercero.setText(d.getTerceros().getNombre());

            articulo.requestFocus();
        } else {
            JOptionPane.showMessageDialog(null, "Tercero no existe");
        }
    }//GEN-LAST:event_terceroActionPerformed

    private void descuentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_descuentoKeyReleased
        // TODO add your handling code here:
        calcularDesceunto();
}//GEN-LAST:event_descuentoKeyReleased

    private void tipodescuentoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tipodescuentoItemStateChanged
        // TODO add your handling code here:
        calcularDesceunto();
}//GEN-LAST:event_tipodescuentoItemStateChanged

    private void restaurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restaurarActionPerformed
        // TODO add your handling code here:
        reiniciar();
}//GEN-LAST:event_restaurarActionPerformed

    private void guardar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardar1ActionPerformed
        // TODO add your handling code here:
        boolean sw = true;
        d.setTipo(3);

        if (validar()) {
            if (funcion == 1) {
                if (d.getNumero().equals(numero.getText())) {
                    guardar2();
                    sw = false;
                }
            }
            if (sw) {
                if (!md.existeDocumento("numero", numero.getText())) {
                    guardar2();
                } else {
                    JOptionPane.showMessageDialog(null, "Numero de Factura ya exsiste");
                }
            }
        }
    }//GEN-LAST:event_guardar1ActionPerformed

    public void guardar2() {

        Facturapropiedades fp = mc.getFacturaporpiedades("1");

        d.setNumero((fp.getNumeroactual() + 1) + "");
        d.setFecha(new Date(fecha.getText().replaceAll("-", "/")));
        d.setTotal(Double.parseDouble(total.getText().replaceAll(",", "")));
        d.setSubtotal(Double.parseDouble(subtotal.getText().replaceAll(",", "")));
        d.setNota(nota.getText());

        d.setTipo(3);

        d.setDescuento(0.0);
        d.setTipodescuento(tipodescuento.getSelectedIndex());
        if (!descuento.getText().trim().equals("")) {
            if (Double.parseDouble(descuento.getText().replaceAll(",", "")) >= 0) {
                double des = Double.parseDouble(total.getText().replaceAll(",", ""));
                d.setDescuento(Double.parseDouble(descuento.getText().replaceAll(",", "")));
            }
        }
        if (d.getTipo() == 3) {
            int op = Formulario_Cobrar_Ventas.cobrar(new JFrame(), d, total.getText());
            if (op > 0) {
                List<Articulosdocumento> la = new LinkedList();
                List<Movimientokardex> lmk = new LinkedList();
                List<Alquileres> lal = new LinkedList();
                List<Detallefactura> ldf = new LinkedList();

                if (d.getAlquileresCollection() != null) {
                    for (int i = 0; i < d.getAlquileresCollection().size(); i++) {
                        md.eliminar(d.getAlquileresCollection().get(i));
                    }
                }

                if (d.getArticulosdocumentoCollection() != null) {
                    for (int i = 0; i < d.getArticulosdocumentoCollection().size(); i++) {
                        md.eliminar(d.getArticulosdocumentoCollection().get(i));
                    }
                }

                for (int i = 0; i < tabla.getRowCount(); i++) {

                    if (tabla.getValueAt(i, 0) instanceof Alquileres) {
                        Alquileres al = (Alquileres) tabla.getValueAt(i, 0);
                        al.setEstado(1);
                        al.setDocumento(d);
                        lal.add(al);

                        Detallefactura df = new Detallefactura();
                        df.setDocumento(d);
                        df.setCodigo(al.getArticulo().getCodigobarras() + "");
                        df.setCantidad((double) al.getCantidad());
                        df.setVlrunit(al.getVlrunitario());
                        df.setVlrparcial(al.getTotal());
                        df.setDescripcion("Alquiler de " + al.getArticulo().getDescripcioncomercial());
                        ldf.add(df);

                    } else {
                        Articulosdocumento ad = (Articulosdocumento) tabla.getValueAt(i, 0);
                        ad.setDocumento(d);
                        la.add(ad);
                        Articulos art = ad.getArticulo();

                        art.setSaldocosto(art.getSaldocosto() - (ad.getCantidad() * art.getVlrpromedio()));
                        art.setVlrpromedio(art.getSaldocosto() / art.getExistencia().longValue());

                        if ((art.getSaldoventa() - (ad.getVlrparcial())) > 0) {
                            art.setSaldoventa(art.getSaldoventa() - (ad.getVlrparcial()));
                            art.setVlrpromediov(art.getSaldoventa() / art.getExistencia().longValue());
                        } else {
                            art.setSaldoventa(0.0);
                            if (art.getExistencia().longValue() == 0) {
                                art.setVlrpromediov(0.0);
                            } else {
                                art.setSaldoventa(art.getVlrpromediov() * art.getExistencia().longValue());
                            }
                        }
                        ma.modificar(art);
                        Movimientokardex mk = new Movimientokardex();
                        mk.setArticulo(ad.getArticulo());
                        mk.setDocumento(d);
                        mk.setEntrada(0.0);
                        mk.setSalida(ad.getCantidad());
                        mk.setVlrunit(ad.getArticulo().getVlrpromedio());
                        mk.setExistencia(ad.getArticulo().getExistencia());
                        mk.setFecha(new Date());
                        mk.setSaldo(ad.getArticulo().getExistencia().longValue() * ad.getArticulo().getVlrpromedio());
                        mk.setTercero(d.getTerceros().getNit() + "");
                        if (d.getTerceros().getId() == 1) {
                            mk.setTercero("Cliente por Mostrador");
                        }
                        mk.setDescripcion("Factura " + d.getNumero());
                        lmk.add(mk);


                        Detallefactura df = new Detallefactura();
                        df.setDocumento(d);
                        df.setCodigo(art.getCodigobarras() + "");
                        df.setCantidad(ad.getCantidad());
                        df.setVlrunit(ad.getVlrunitario());
                        df.setVlrparcial(ad.getVlrparcial());
                        df.setDescripcion(art.getDescripcioncomercial());
                        ldf.add(df);

                    }
                }

                if (d.getTipopago() == 3) {
                    List<Abonos> lab = new LinkedList();
                    Abonos ab = new Abonos();
                    ab.setDocumentos(d);
                    ab.setFecha(d.getFecha());
                    ab.setValor(d.getTotalpagado());
                    lab.add(ab);
                    d.setAbonosList(lab);
                }

                d.setMovimientokardexCollection(lmk);
                d.setArticulosdocumentoCollection(la);
                d.setDetallefacturaList(ldf);
                d.setAlquileresCollection(lal);

                if (funcion == 0) {
                    fp.setNumeroactual(fp.getNumeroactual() + 1);
                    mc.modificar(fp);
                    md.crear(d);
                } else {
                    md.modificar(d);
                }

                b.buscar();
                this.dispose();

                if (op == 2) {
                    managers.Reporte.imprimir(d, mc);
                }
                JOptionPane.showMessageDialog(null, "Datos guardados con exito");
            }
        }
    }

    private void agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarActionPerformed
        // TODO add your handling code here:
        Abonos a = FormularioAbonar.abonar(parent, true);
        if (a != null) {
            if ((d.getTotalpagado() + a.getValor()) <= d.getTotal()) {
                a.setDocumentos(d);
                d.getAbonosList().add(a);

                if ((d.getTotalpagado() + a.getValor()) == d.getTotal()) {
                    d.setEstado(1);
                    agregar.setEnabled(false);
                }
                d.setTotalpagado(d.getTotalpagado() + a.getValor());
                md.modificar(d);
                mtabonos.addRow(new Object[]{a.getFecha(), utilidades.FormatoNumeros.formatear("" + a)});
                totalpagado.setText(utilidades.FormatoNumeros.formatear(d.getTotalpagado() + ""));
                saldo.setText(utilidades.FormatoNumeros.formatear((d.getTotal() - d.getTotalpagado()) + ""));
            } else {
                JOptionPane.showMessageDialog(null, "El valor abonar mas el total abonado supera el valor de la factura");
            }
        }
}//GEN-LAST:event_agregarActionPerformed

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        // TODO add your handling code here:
        int index = tabla.getSelectedRow();
        if (index > -1) {
            ad = Ventana_Editar_Item.editarItem(parent, true, (Articulosdocumento) tabla.getValueAt(index, 0), 1);
            if (ad != null) {
                tabla.setValueAt(ad, index, 0);
                String descrip = ad.getArticulo() + "";
                if (ad.getArticulo().getTipo() == 1) {
                    descrip = "Servicio de " + ad.getArticulo().getDescripcioncomercial();
                }
                tabla.setValueAt(descrip, index, 1);
                tabla.setValueAt(ad.getCantidad(), index, 2);
                tabla.setValueAt(utilidades.FormatoNumeros.formatear("" + ad.getVlrunitario()), index, 3);
                tabla.setValueAt(utilidades.FormatoNumeros.formatear("" + ad.getVlrparcial()), index, 4);
                ad = null;
            }
        }
    }//GEN-LAST:event_tablaMouseClicked

    private void descuentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_descuentoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_descuentoActionPerformed

    private void vunitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vunitActionPerformed
        // TODO add your handling code here:
        if (!cantidad.getText().trim().equals("")) {
            double cantidades = Double.parseDouble(cantidad.getText());
            if (ad != null) {
                long existencia = ad.getArticulo().getExistencia().longValue();

                double vltunitario = Double.parseDouble(vunit.getText().replaceAll(",", ""));
                if (vltunitario >= ad.getArticulo().getValormin()) {
                    double totalparcial = cantidades * (vltunitario);
                    vparcial.setText(utilidades.FormatoNumeros.formatear("" + (totalparcial)));
                    adicionar.requestFocus();
                } else {
                    JOptionPane.showMessageDialog(null, "El Articulo no puede ser vendio con un valor inferior al minimo de venta");
                }
            }
        }
    }//GEN-LAST:event_vunitActionPerformed

    public void calcularDesceunto() {
        if (!descuento.getText().trim().equals("")) {
            double t = Double.parseDouble(subtotal.getText().replaceAll(",", ""));
            double dev = Double.parseDouble(descuento.getText().replaceAll(",", ""));
            if (tipodescuento.getSelectedIndex() == 0) {
                dev = t - dev / 100 * t;
            } else {
                dev = t - dev;
            }
            if (dev >= 0) {
                total.setText(utilidades.FormatoNumeros.formatear(dev + ""));
            }
        }
    }

    public void reiniciar() {

        d = new Documentos();
        mt = new DefaultTableModel();
        mt.addColumn("Codigo");
        mt.addColumn("Descripcion");
        mt.addColumn("Cantidad");
        mt.addColumn("Vlr Unit");
        mt.addColumn("Vlr Par");
        tabla.setModel(mt);
        Terceros t = md.getTercero("1");
        if (t != null) {
            d.setTerceros(t);
            tercero.setText(t.getNombre());
            ntercero.setText(t.getNombre());
        } else {
            JOptionPane.showMessageDialog(null, "no se ha establecido un cliente por mostrador");
            guardar.setEnabled(false);
        }


        int ano = Calendar.getInstance().get(Calendar.YEAR);
        int mes = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int dia = Calendar.getInstance().get(Calendar.DATE);

        fecha.setText(ano + "-" + mes + "-" + dia);

        Facturapropiedades fp = mc.getFacturaporpiedades("1");
        if (fp != null) {
            int consecutivo = fp.getNumeroactual() + 1;
            numero.setText(consecutivo + "");
        } else {
            JOptionPane.showMessageDialog(null, "no se ha Configuarado las propiedades de la factura");
            guardar.setEnabled(false);
        }

        ad = null;
        adicionar.setEnabled(false);
        articulo.setText("");

        cantidad.setText("1");
        vunit.setText("0.00");
        vparcial.setText("0.00");
        articulo.requestFocus();
        descuento.setText("0.00");
        total.setText("0.00");
        subtotal.setText("0.00");
    }

    public boolean esta(Object a) {
        for (int i = 0; i < tabla.getRowCount(); i++) {
            if (tabla.getValueAt(i, 0).equals(a)) {
                return true;
            }
        }
        return false;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton adicionar;
    private javax.swing.JButton agregar;
    private javax.swing.JTextField articulo;
    private javax.swing.JButton buscafecha;
    private javax.swing.JButton buscaproveedor;
    private javax.swing.JButton buscara;
    private javax.swing.JTextField cantidad;
    private javax.swing.JTextField descuento;
    private javax.swing.JTextField fecha;
    private javax.swing.JButton guardar;
    private javax.swing.JButton guardar1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField nota;
    private javax.swing.JTextField ntercero;
    private javax.swing.JTextField numero;
    private javax.swing.JPanel panelabonos;
    private javax.swing.JButton quitar;
    private javax.swing.JButton restaurar;
    private javax.swing.JLabel saldo;
    private javax.swing.JButton salir;
    private javax.swing.JTextField subtotal;
    private javax.swing.JTabbedPane tab;
    private javax.swing.JTable tabla;
    private javax.swing.JTable tablaabonos;
    private javax.swing.JTextField tercero;
    private javax.swing.JComboBox tipo;
    private javax.swing.JComboBox tipodescuento;
    private javax.swing.JLabel total;
    private javax.swing.JLabel totalpagado;
    private javax.swing.JTextField vparcial;
    private javax.swing.JTextField vunit;
    // End of variables declaration//GEN-END:variables
}
*/